﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;



namespace Portal
{
    public static class SessionBuilder
    {
        private static readonly object Locker = new object();
        private static Configuration _configuration = null;
        private static ISessionFactory _sessionFactory = null;
        public static ISessionStorage SessionStorage { set; get; }

        private static void CreateConfiguration()
        {
            // HibernatingRhinos.NHibernate.Profiler.Appender.NHibernateProfiler.Initialize();//查看HQL生成的SQL
            //configuration = new Configuration().Configure(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "Configuration\\hibernate.cfg.xml");
            _configuration = new Configuration().Configure(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "Configuration\\Nhm\\hibernate.cfg.xml");
            Configuration.LinqToHqlGeneratorsRegistry<MyLinqToHqlGeneratorsRegistry>();


        }
        public static Configuration Configuration
        {
            get
            {
                lock (Locker)
                {
                    if (_configuration == null)
                    {
                        CreateConfiguration();
                    }
                    return _configuration;
                }
            }
            set { _configuration = value; }
        }

        internal static ISessionFactory SessionFactory
        {
            get
            {
                if (_sessionFactory == null)
                {
                    if (Configuration == null)
                    {
                        CreateConfiguration();
                    }
                    lock (Locker)
                    {
                        if (Configuration != null) _sessionFactory = Configuration.BuildSessionFactory();
                    }
                }

                return _sessionFactory;
            }
        }

        public static ISession CreateSession()
        {
            ISession s = SessionStorage.Get();
            if (s == null)
            {
                s = SessionFactory.OpenSession();
                SessionStorage.Set(s);
            }
            return s;
        }

    }
}
